package com.jnu.hospitalexamination.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.jnu.hospitalexamination.annotation.JwtAuth;
import com.jnu.hospitalexamination.common.Result;
import com.jnu.hospitalexamination.dto.OrdersUserQueryDTO;
import com.jnu.hospitalexamination.dto.UserLoginDTO;
import com.jnu.hospitalexamination.dto.UserRegisterDTO;
import com.jnu.hospitalexamination.entity.Users;
import com.jnu.hospitalexamination.entity.vo.UserLoginVO;
import com.jnu.hospitalexamination.service.UsersService;
import com.jnu.hospitalexamination.utils.JwtUtil;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.UUID;

@RestController
@RequestMapping("/user")
public class UserController {
    private static final Logger log = LoggerFactory.getLogger(UserController.class);
    @Autowired
    private UsersService usersService;

    /**
     * 根据userId查询用户信息
     * @param userId
     * @return user对象
     */
    @RequestMapping("/getUserInfo")
    public Result getUserInfo(Integer userId) {
        Users user = usersService.getById(userId);
        if (user != null) {
            return Result.success(200, "查询成功", user);
        } else {
            return Result.error(400, "查询失败", null);
        }
    }
//    根据用户信息查询用户预约

    /**
     * 根据用户信息查询用户预约
     * @param ordersUserQueryDTO
     * @return
     */
    @RequestMapping("/getUserOrder")
    public Result getUserOrder(OrdersUserQueryDTO ordersUserQueryDTO) {
        try {
            return Result.success(200, "查询成功", usersService.findUserByConditions(ordersUserQueryDTO.getPhone(), ordersUserQueryDTO.getRealName(), ordersUserQueryDTO.getSex(), ordersUserQueryDTO.getSmId(), ordersUserQueryDTO.getOrderDate(), ordersUserQueryDTO.getState()));
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(400, "查询失败"+e.getMessage(), null);
        }
    }
    @JwtAuth
    @PostMapping("/login")
    public Result login(@RequestBody  UserLoginDTO userLoginDTO, HttpServletResponse response) {
        String phone = userLoginDTO.getPhone();
        log.info("登录请求："+ phone);
        LambdaQueryWrapper<Users> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Users::getPhone, phone)
                .eq(Users::getPassword, userLoginDTO.getPassword());
        Users user = usersService.getOne(lambdaQueryWrapper);

        if (user == null) {
            return Result.success(4001,"用户名或密码错误",null);
        }
        try{
//            user.setPassword(null);
            JwtBuilder builder = Jwts.builder();
            builder.setId(UUID.randomUUID().toString());
            builder.setIssuedAt(new Date());
            // 过期函数
            builder.setExpiration(new Date(System.currentTimeMillis()+1000*60*60));
            builder.signWith(SignatureAlgorithm.HS256, "666222");
            UserLoginVO userLoginVO = new UserLoginVO();
            userLoginVO.setPassword(user.getPassword());
            userLoginVO.setUserid(user.getUserid());
            userLoginVO.setRealname(user.getRealname());
            userLoginVO.setPhone(user.getPhone());
            userLoginVO.setBalance(user.getBalance());
            userLoginVO.setBirthday(user.getBirthday());
            userLoginVO.setSex(user.getSex());
            userLoginVO.setIdentitycard(user.getIdentitycard());
            //String token = JwtUtil.generateToken(user.getRealname());
            builder.claim("userId", user.getRealname());
            builder.claim("phone",user.getPhone());
            builder.claim("identitycard",user.getIdentitycard());
            builder.setSubject(user.getUserid()+"");
            String token = builder.compact();
            userLoginVO.setToken(token);
            response.setHeader("Authorization",token);
            log.info("登录成功："+ phone);
            return Result.success(200, "登录成功", userLoginVO);
        } catch (Exception ex){
            ex.printStackTrace();
            log.error(phone+"登录异常："+ex.getMessage());
            return Result.error(5000,"登录失败："+ex.getMessage(),null);
        }
    }

    @PostMapping("/register")
    public Result register(@RequestBody UserRegisterDTO userRegisterDTO) {

        Users user = new Users();
        user.setPhone(userRegisterDTO.getPhone());
        user.setPassword(userRegisterDTO.getPassword());
        user.setRealname(userRegisterDTO.getRealname());
        user.setIdentitycard(userRegisterDTO.getIdentitycard());
        user.setBirthday(userRegisterDTO.getBirthday());
        user.setSex(userRegisterDTO.getSex());
        user.setUsertype(1);
        if( usersService.save(user)){
            user.setPassword(null);
            UserLoginVO userLoginVO = new UserLoginVO();
            userLoginVO.setPassword(user.getPassword());
            userLoginVO.setUserid(user.getUserid());
            userLoginVO.setRealname(user.getRealname());
            userLoginVO.setPhone(user.getPhone());
            userLoginVO.setBalance(user.getBalance());
            userLoginVO.setBirthday(user.getBirthday());
            userLoginVO.setSex(user.getSex());
            userLoginVO.setIdentitycard(user.getIdentitycard());
            String token = JwtUtil.generateToken(user.getRealname());
            userLoginVO.setToken(token);


            return Result.success(200, "注册成功", userLoginVO);
        }

        return Result.error(400, "注册失败", null);

    }
    @Transactional
    @JwtAuth
    @RequestMapping("/pay")
    public Result pay(Integer userId, Integer amount) {
        try {
            Users user = new Users();
            user.setUserid(userId);
            Integer balance = usersService.getById(userId).getBalance();
            if (amount>balance){
                return Result.error(500, "支付失败，余额不足，余额剩余："+usersService.getById(userId).getBalance()+"元", null);
            }
            user.setBalance(balance-amount);
            usersService.updateById(user);
            return Result.success(200, "支付成功，余额剩余："+usersService.getById(userId).getBalance()+"元", user);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(400, "支付失败："+e.getMessage(), null);
        }
    }
}
